import { defineComponent, reactive, ref, watch, onMounted } from "vue";
import styles from "./ChordSet.module.less";
import beats from "@/common/dicts/beats";
import { getScoreToneChoose, getChooseScore } from "@/common/utils/getScoreToneChoose";
import { $musicSongChords } from "@/apis/music/songChords/songChords";
import to from "await-to-js";
import { message } from "ant-design-vue";
export default defineComponent({
  props: {
    state: {
      type: Object,
    },
  },
  emits: ['confirm'],
  setup(props, { expose, emit }) {
    const state = reactive({
      isOpen: false,
      beat: "960",
      chooseOri: null,
      chord_tone: "C",
    })
    const chords = ref([] as any[]);
    const open = (e) => {
      state.beat = e.beat || "960";
      state.chooseOri = e.chooseOri || null;
      state.isOpen = true;
      state.chord_tone = e.chord_tone || "C";
    }
    const confirm = () => {
      if (!state.beat) {
        message.error("请输入节拍!");
        return;
      }
      if (!state.chooseOri) {
        message.error("请输入和弦!");
        return;
      }
      const choose = getScoreToneChoose(state.chooseOri, state.chord_tone ? state.chord_tone : 'C', chords.value);
      if (!choose) {
        message.error("输入的和弦有误!")
        return;
      }
      const chooseScore = getChooseScore(choose, props.state?.score_tone, chords.value);
      emit("confirm", {
        beat: state.beat,
        choose,
        chooseOri: state.chooseOri,
        chooseScore,
      });
      state.isOpen = false;
    }
    watch(() => state.isOpen, (nv) => {
      if (!nv) {
        state.beat = "960";
        state.chooseOri = null;
      }
    })
    // 获取所有和弦
    const getChords = async () => {
      const [err, res]: any = await to($musicSongChords());
      if (!err) {
        chords.value = res?.data?.data || [];
      }
    }
    onMounted(() => {
      getChords();
    })
    expose({
      open,
    })
    return () => (
      state.isOpen &&
      <div class={styles.chordSetFloating}>
        <div class={styles.chordSetCard}>
          <div class={styles.header}>设置和弦</div>
          <div class={styles.container}>
            <a-input style={{ width: "100%" }} v-model:value={state.chooseOri} placeholder="请输入和弦" />
            <a-radio-group style={{ width: "100%", marginTop: "15px" }} v-model:value={state.beat} button-style="solid">
              {
                beats.map((item) => (
                  <a-radio-button value={item.value}>{item.label}</a-radio-button>
                ))
              }
            </a-radio-group>
          </div>
          <div class={styles.footer}>
            <a-button onClick={() => { state.isOpen = false }}>取消</a-button>
            <a-button type="primary" onClick={() => { confirm() }}>确认</a-button>
          </div>
        </div>
      </div>
    )
  }
})